{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Role Prompting Tutorial\n",
    "\n",
    "## Overview\n",
    "\n",
    "This tutorial explores the concept of role prompting in AI language models, focusing on how to assign specific roles to AI models and craft effective role descriptions. We'll use OpenAI's GPT model and the LangChain library to demonstrate these techniques.\n",
    "\n",
    "## Motivation\n",
    "\n",
    "Role prompting is a powerful technique in prompt engineering that allows us to guide AI models to adopt specific personas or expertise. This approach can significantly enhance the quality and relevance of AI-generated responses, making them more suitable for specific tasks or domains.\n",
    "\n",
    "## Key Components\n",
    "\n",
    "1. Role Assignment: Techniques for assigning roles to AI models\n",
    "2. Role Description Crafting: Strategies for creating effective and detailed role descriptions\n",
    "3. Context Setting: Methods to provide necessary background information for the role\n",
    "4. Task Specification: Approaches to clearly define tasks within the assigned role\n",
    "\n",
    "## Method Details\n",
    "\n",
    "Our approach involves the following steps:\n",
    "\n",
    "1. Setting up the environment with necessary libraries (OpenAI, LangChain)\n",
    "2. Creating role-based prompts using LangChain's PromptTemplate\n",
    "3. Assigning roles to the AI model through carefully crafted prompts\n",
    "4. Demonstrating how different roles affect the model's responses\n",
    "5. Exploring techniques for refining and improving role descriptions\n",
    "\n",
    "We'll use various examples to illustrate how role prompting can be applied in different scenarios, such as technical writing, creative storytelling, and professional advice-giving.\n",
    "\n",
    "## Conclusion\n",
    "\n",
    "By the end of this tutorial, you will have a solid understanding of role prompting techniques and how to effectively implement them using OpenAI and LangChain. You'll be equipped with the skills to craft compelling role descriptions and leverage them to enhance AI model performance in various applications."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup\n",
    "\n",
    "First, let's import the necessary libraries and set up our environment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "from dotenv import load_dotenv\n",
    "load_dotenv()\n",
    "\n",
    "# Set up OpenAI API key\n",
    "os.environ[\"OPENAI_API_KEY\"] = os.getenv('OPENAI_API_KEY')\n",
    "\n",
    "# Initialize the language model\n",
    "llm = ChatOpenAI(model=\"gpt-4o-mini\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Basic Role Assignment\n",
    "\n",
    "Let's start with a simple example of role assignment. We'll create a prompt that assigns the role of a technical writer to the AI model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Cloud computing is a technology that allows you to store and access data and applications over the internet instead of your computer's hard drive. This means you can use software and files from anywhere, at any time, as long as you have an internet connection. It offers flexibility, scalability, and convenience for both personal and professional use.\n"
     ]
    }
   ],
   "source": [
    "tech_writer_prompt = PromptTemplate(\n",
    "    input_variables=[\"topic\"],\n",
    "    template=\"\"\"You are a technical writer specializing in creating clear and concise documentation for software products.\n",
    "    Your task is to write a brief explanation of {topic} for a user manual.\n",
    "    Please provide a 2-3 sentence explanation that is easy for non-technical users to understand.\"\"\"\n",
    ")\n",
    "\n",
    "chain = tech_writer_prompt | llm\n",
    "response = chain.invoke({\"topic\": \"cloud computing\"})\n",
    "print(response.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Crafting Effective Role Descriptions\n",
    "\n",
    "Now, let's explore how to craft more detailed and effective role descriptions. We'll create a prompt for a financial advisor role with a more comprehensive description."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Given your solid income and savings, the first step is to establish a retirement plan. Consider contributing to a tax-advantaged retirement account, like a 401(k) or an IRA, to take advantage of compounding interest and potential employer match. Additionally, aim to build an emergency fund covering 3-6 months of living expenses to enhance your financial stability. Lastly, regularly review and adjust your investment strategy to align with your long-term financial goals, ensuring a balanced approach to risk and growth.\n"
     ]
    }
   ],
   "source": [
    "financial_advisor_prompt = PromptTemplate(\n",
    "    input_variables=[\"client_situation\"],\n",
    "    template=\"\"\"You are a seasoned financial advisor with over 20 years of experience in personal finance, investment strategies, and retirement planning.\n",
    "    You have a track record of helping clients from diverse backgrounds achieve their financial goals.\n",
    "    Your approach is characterized by:\n",
    "    1. Thorough analysis of each client's unique financial situation\n",
    "    2. Clear and jargon-free communication of complex financial concepts\n",
    "    3. Ethical considerations in all recommendations\n",
    "    4. A focus on long-term financial health and stability\n",
    "\n",
    "    Given the following client situation, provide a brief (3-4 sentences) financial advice:\n",
    "    {client_situation}\n",
    "\n",
    "    Your response should reflect your expertise and adhere to your characteristic approach.\"\"\"\n",
    ")\n",
    "\n",
    "chain = financial_advisor_prompt | llm\n",
    "response = chain.invoke({\"client_situation\": \"A 35-year-old professional earning $80,000 annually, with $30,000 in savings, no debt, and no retirement plan.\"})\n",
    "print(response.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparing Responses with Different Roles\n",
    "\n",
    "To demonstrate how different roles can affect the AI's responses, let's create prompts for three different roles and compare their outputs on the same topic."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Scientist's explanation:\n",
      "\n",
      "The greenhouse effect is a natural process that warms the Earth’s surface. It occurs when the Sun’s energy reaches the Earth’s atmosphere — some of this energy is reflected back to space and the rest is absorbed and re-radiated by greenhouse gases.\n",
      "\n",
      "Here's a more detailed breakdown of the process:\n",
      "\n",
      "1. **Solar Radiation**: The Sun emits energy in the form of solar radiation, which includes visible light, ultraviolet light, and infrared radiation. When this energy reaches Earth, about 30% is reflected back into space by clouds, atmospheric particles, and reflective surfaces (like ice and snow). The remaining 70% is absorbed by the Earth's surface (land and oceans), which warms the surface.\n",
      "\n",
      "2. **Re-radiation of Heat**: The Earth, having absorbed solar energy, warms up and subsequently emits energy back into the atmosphere in the form of infrared radiation (heat). This is a crucial step as it transforms solar energy into thermal energy.\n",
      "\n",
      "3. **Greenhouse Gases**: Certain gases in the atmosphere, known as greenhouse gases (GHGs), trap some of the outgoing infrared radiation. The most significant greenhouse gases include carbon dioxide (CO₂), methane (CH₄), nitrous oxide (N₂O), and water vapor (H₂O). These gases have molecular structures that allow them to absorb and re-radiate infrared radiation, effectively trapping heat within the atmosphere.\n",
      "\n",
      "4. **Enhanced Greenhouse Effect**: While the greenhouse effect is a natural and essential process that maintains Earth's temperature at a level conducive to life, human activities, particularly the burning of fossil fuels, deforestation, and industrial processes, have led to an increase in the concentration of greenhouse gases. This enhanced greenhouse effect results in more heat being retained in the atmosphere, leading to global warming and climate change.\n",
      "\n",
      "5. **Climate Impacts**: The increase in average global temperatures affects climate systems, leading to more extreme weather events, rising sea levels, and disruptions to ecosystems and biodiversity.\n",
      "\n",
      "In summary, the greenhouse effect is a fundamental component of the Earth’s climate system, facilitating a habitable environment by regulating temperature. However, anthropogenic increases in greenhouse gas concentrations are intensifying this natural effect, resulting in significant environmental changes and challenges.\n",
      "--------------------------------------------------\n",
      "\n",
      "Teacher's explanation:\n",
      "\n",
      "Sure! Let’s imagine the Earth as a big greenhouse, which is a special building that helps plants grow by keeping them warm and cozy. Here's how the greenhouse effect works:\n",
      "\n",
      "1. **Sunshine**: The Sun shines down on the Earth, sending light and warmth our way. This is like the sunlight coming into a greenhouse.\n",
      "\n",
      "2. **Earth’s Surface**: When the sunlight hits the ground, buildings, and even the ocean, it warms them up. Just like how the inside of a greenhouse gets warm when the sun shines on it.\n",
      "\n",
      "3. **Heat Trapped**: Now, the Earth doesn’t just keep all that heat. Some of it tries to escape back into space. However, there are certain gases in our atmosphere, called greenhouse gases (like carbon dioxide and methane), that act like a blanket. They trap some of this heat, keeping the Earth warm enough for us to live.\n",
      "\n",
      "4. **Balance is Key**: This natural process is important because it keeps our planet at a temperature that's just right for plants, animals, and us humans! Without the greenhouse effect, Earth would be way too cold.\n",
      "\n",
      "5. **Too Much of a Good Thing**: But here’s the catch: if we add too many greenhouse gases (from things like cars, factories, and cutting down trees), it makes the blanket too thick. This causes the Earth to warm up too much, leading to climate change. That's why we need to be careful about how we treat our planet!\n",
      "\n",
      "So, the greenhouse effect is like having a warm blanket around our Earth, helping keep it cozy, but we need to make sure it’s not too thick!\n",
      "--------------------------------------------------\n",
      "\n",
      "Journalist's explanation:\n",
      "\n",
      "**Understanding the Greenhouse Effect: Nature's Cozy Blanket**\n",
      "\n",
      "Imagine stepping outside on a chilly winter day, wrapping yourself in a warm blanket to stave off the cold. This is similar to what our planet experiences through a natural phenomenon known as the greenhouse effect. While it plays a crucial role in maintaining life as we know it, understanding its mechanics is key to grasping the challenges our world faces today.\n",
      "\n",
      "So, what exactly is the greenhouse effect? At its core, it’s a process that helps regulate Earth's temperature, ensuring it’s just right for plants, animals, and humans. Here’s how it works:\n",
      "\n",
      "1. **Sunshine and Absorption**: The journey begins with the Sun, which bathes our planet in energy. When sunlight reaches Earth, some of it is absorbed by the land and oceans, warming the surface. Think of this as the Earth soaking up warmth like a sponge.\n",
      "\n",
      "2. **Radiation Back to Space**: After absorbing this energy, the Earth doesn’t keep all the heat. Instead, it radiates some of it back into space in the form of infrared radiation (a type of heat). It’s like that sponge, once full, starts to release moisture back into the air.\n",
      "\n",
      "3. **The Greenhouse Gases**: Here’s where the greenhouse effect truly comes into play. Our atmosphere is not just empty air; it contains a mix of gases, some of which are known as greenhouse gases—primarily carbon dioxide (CO2), methane (CH4), and water vapor. These gases are like the insulating layers of your cozy blanket. They trap some of the outgoing infrared radiation, preventing it from escaping back into space. This process keeps our planet warm enough to support life.\n",
      "\n",
      "4. **The Balance**: Under natural conditions, this balance is maintained. The amount of heat entering the atmosphere is roughly equal to the amount being trapped and radiated back out. This equilibrium has allowed Earth to maintain a stable climate for thousands of years.\n",
      "\n",
      "However, human activities—such as the burning of fossil fuels, deforestation, and industrial processes—have tipped this delicate balance. By releasing additional greenhouse gases into the atmosphere, we enhance the greenhouse effect, causing more heat to be trapped. This is akin to adding extra layers to your blanket when you’re already warm; soon, you’re too hot.\n",
      "\n",
      "The consequences of this intensified greenhouse effect are profound. We are witnessing rising global temperatures, melting ice caps, and shifting weather patterns, all of which contribute to climate change. These changes can lead to severe weather events, rising sea levels, and disruptions to ecosystems, impacting food security, water supply, and human health.\n",
      "\n",
      "Understanding the greenhouse effect is crucial not just for grasping climate science, but also for motivating action. As we learn more about how our actions contribute to this phenomenon, it becomes clear that we have the power to influence the outcome. By reducing our carbon footprint—through renewable energy, energy efficiency, and sustainable practices—we can help restore balance to our planet’s climate system.\n",
      "\n",
      "In essence, the greenhouse effect is a reminder of the intricate connections within our environment. It highlights the delicate balance we must maintain to ensure that Earth remains a hospitable home for all its inhabitants. So, as we wrap ourselves in our metaphorical blankets, let’s do so with mindfulness, ensuring we don’t overdo it and keep our planet’s temperature just right.\n",
      "--------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "roles = [\n",
    "    (\"Scientist\", \"You are a research scientist specializing in climate change. Explain the following concept in scientific terms:\"),\n",
    "    (\"Teacher\", \"You are a middle school science teacher. Explain the following concept in simple terms suitable for 12-year-old students:\"),\n",
    "    (\"Journalist\", \"You are a journalist writing for a popular science magazine. Explain the following concept in an engaging and informative manner for a general adult audience:\")\n",
    "]\n",
    "\n",
    "topic = \"The greenhouse effect\"\n",
    "\n",
    "for role, description in roles:\n",
    "    role_prompt = PromptTemplate(\n",
    "        input_variables=[\"topic\"],\n",
    "        template=f\"{description} {{topic}}\"\n",
    "    )\n",
    "    chain = role_prompt | llm\n",
    "    response = chain.invoke({\"topic\": topic})\n",
    "    print(f\"\\n{role}'s explanation:\\n\")\n",
    "    print(response.content)\n",
    "    print(\"-\" * 50)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Refining Role Descriptions\n",
    "\n",
    "Let's explore how to refine role descriptions for more specific outcomes. We'll use a creative writing example, focusing on different storytelling styles."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Gothic horror version:\n",
      "\n",
      "As twilight draped its somber veil over the forsaken dwelling, the air thickened with the scent of mold and memories long buried beneath layers of dust and despair. The door creaked open with a mournful groan, revealing a cavernous interior, where shadows danced like specters in the fading light, whispering secrets of the long-dead inhabitants. Each step echoed ominously on the rotting floorboards, a grim reminder of the decay that had claimed both structure and spirit, while a chill snaked around the intruder’s heart, tightening with the realization that they were not alone. In that suffocating gloom, the very walls seemed to pulse with a malignant energy, as if the house itself hungered for a soul to ensnare in its eternal grasp of sorrow.\n",
      "--------------------------------------------------\n",
      "\n",
      "Minimalist realism version:\n",
      "\n",
      "The door creaked as she pushed it open, the sound swallowed by the stillness. Shadows pooled in corners, stretching across the faded floorboards. She paused, breath caught in the quiet, the air thick with dust and memories. Outside, the sky deepened to indigo, while inside, time seemed to linger, waiting.\n",
      "--------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "storyteller_prompt = PromptTemplate(\n",
    "    input_variables=[\"style\", \"scenario\"],\n",
    "    template=\"\"\"You are a master storyteller known for your ability to adapt to various narrative styles.\n",
    "    Your current task is to write in the style of {style}.\n",
    "    Key characteristics of this style include:\n",
    "    1. {style_char1}\n",
    "    2. {style_char2}\n",
    "    3. {style_char3}\n",
    "\n",
    "    Write a short paragraph (3-4 sentences) in this style about the following scenario:\n",
    "    {scenario}\n",
    "\n",
    "    Ensure your writing clearly reflects the specified style.\"\"\"\n",
    ")\n",
    "\n",
    "styles = [\n",
    "    {\n",
    "        \"name\": \"Gothic horror\",\n",
    "        \"char1\": \"Atmospheric and ominous descriptions\",\n",
    "        \"char2\": \"Themes of decay, death, and the supernatural\",\n",
    "        \"char3\": \"Heightened emotions and sense of dread\"\n",
    "    },\n",
    "    {\n",
    "        \"name\": \"Minimalist realism\",\n",
    "        \"char1\": \"Sparse, concise language\",\n",
    "        \"char2\": \"Focus on everyday, ordinary events\",\n",
    "        \"char3\": \"Subtle implications rather than explicit statements\"\n",
    "    }\n",
    "]\n",
    "\n",
    "scenario = \"A person enters an empty house at twilight\"\n",
    "\n",
    "for style in styles:\n",
    "    chain = storyteller_prompt | llm\n",
    "    response = chain.invoke({\n",
    "        \"style\": style[\"name\"],\n",
    "        \"style_char1\": style[\"char1\"],\n",
    "        \"style_char2\": style[\"char2\"],\n",
    "        \"style_char3\": style[\"char3\"],\n",
    "        \"scenario\": scenario\n",
    "    })\n",
    "    print(f\"\\n{style['name']} version:\\n\")\n",
    "    print(response.content)\n",
    "    print(\"-\" * 50)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
